<?php

class Damages_Methods_Request_Edit_CarDamage extends Damages_Methods_Request {

  /**
   *
   * @var Damages_Methods_Data_CarDamage_Edit 
   */
  public $carDamage;

  public function __construct($params) {
    parent::__construct($params);
    $this->carDamage = new Damages_Methods_Data_CarDamage_Edit($params->carDamage);
  }

  public function process() {
    if (!$this->carDamage->validate())
      throw new Damages_Exception_App(Damages_Codes::INVALID_NEW_DAMAGE);
    $carDamage = DamagesCarDamagesQuery::create()->findOneById($this->carDamage->id);
    if (!$carDamage)
      throw new Damages_Exception_App(Damages_Codes::DB_OBJECT_NOT_FOUND);
    $carData = $carDamage->getCarData();
    $con = Propel::getConnection(Damages_Config::getInstance()->datasource);
    try {
      $con->beginTransaction();
      $carDamage->setStatusId($this->carDamage->status->id);
      $carDamage->setDictPerpetratorId($this->carDamage->perpetrator->id);
      $carDamage->setDamagesDescription($this->carDamage->damageDescription);
      $carDamage->setDescription($this->carDamage->description);
      $carDamage->setDamageDate($this->carDamage->damageDate);
      if ($this->carDamage->ol && $this->carDamage->ol->id)
        $carDamage->setOlId($this->carDamage->ol->id);
      foreach ($this->carDamage->damages as $damage) {
        if ($damage->id) {
          $dbDamage = DamagesDamagesQuery::create()->findOneById($damage->id);
        } else {
          $dbDamage = new DamagesDamages();
          $carDamage->addDamages($dbDamage);
        }
        $dbDamage->setIsMain((int) $damage->isMain);
        $dbDamage->setDictDamageScaleId($damage->scale->id);
        $dbDamage->setDictDamageSpotId($damage->spot->id);
        $dbDamage->setDictDamageTypeId($damage->type->id);
        $dbDamage->save();
      }

      foreach ($this->carDamage->estimatedBudgets as $key => $estimatedBudget) {
        if ($estimatedBudget->id) {
          $dbBudget = DamagesEstimatedBudgetsQuery::create()->findOneById($estimatedBudget->id);
        } else {
          $dbBudget = new DamagesEstimatedBudgets();
          $carDamage->addEstimatedBudgets($dbBudget);
          $attachment = DamagesAttachmentsQuery::create()->findOneById($estimatedBudget->attachment->id);
          $targetDir = Damages_Config::getInstance()->uploads->mainPath . $carData->getVin() . '/' . Damages_Config::getInstance()->uploads->subdirs->estimatedCosts;
          $targetFileName = sprintf(Damages_Config::getInstance()->uploads->patterns->estimatedCosts, $key);
          $attachment = $this->processAttachment($attachment, $targetDir, $targetFileName);
          $dbBudget->setAttachments($attachment);
        }
        $dbBudget->setCarValue($estimatedBudget->carValue);
        $dbBudget->setIsDefault($estimatedBudget->isDefault);
        $dbBudget->setDiscountFlag($estimatedBudget->discountFlag);
        $dbBudget->setDeductionValue($estimatedBudget->deductionValue);
        if ($estimatedBudget->discountFlag) {
          $discountData = Damages_Methods_Request_GetDiscountData::calculateDiscount(
                          $carData->getDictBrandId(), $estimatedBudget->value, $estimatedBudget->deductionValue, $estimatedBudget->carValue
          );
          $dbBudget->setDiscountPercentage($discountData->discountData->discountPercentage);
          $dbBudget->setDiscountValue($discountData->discountData->discountVal);
        }
        $dbBudget->setValue($estimatedBudget->value);
        $dbBudget->save();
      }
      if ($this->carDamage->attachments) {
        if ($this->carDamage->attachments->photos)
          foreach ($this->carDamage->attachments->photos as $key => $photo) {
            $attachment = DamagesAttachmentsQuery::create()->findOneById($photo->id);
            if ($attachment instanceof DamagesAttachments && $attachment->getTemp() == 1) {
              $targetDir = Damages_Config::getInstance()->uploads->mainPath . $carData->getVin() . '/' . Damages_Config::getInstance()->uploads->subdirs->photos;
              $targetFileName = sprintf(Damages_Config::getInstance()->uploads->patterns->photos, $key);
              $attachment = $this->processAttachment($attachment, $targetDir, $targetFileName);
              $attachment->setCarDamageId($this->carDamage->id);
              $attachment->save();
            }
          }
        if ($this->carDamage->attachments->additional)
          foreach ($this->carDamage->attachments->additional as $key => $additional) {
            $attachment = DamagesAttachmentsQuery::create()->findOneById($additional->id);
            if ($attachment instanceof DamagesAttachments && $attachment->getTemp() == 1) {
              $targetDir = Damages_Config::getInstance()->uploads->mainPath . $carData->getVin() . '/' . Damages_Config::getInstance()->uploads->subdirs->additional;
              $targetFileName = sprintf(Damages_Config::getInstance()->uploads->patterns->additional, $key);
              $attachment = $this->processAttachment($attachment, $targetDir, $targetFileName);
              $attachment->setCarDamageId($this->carDamage->id);
              $attachment->save();
            }
          }
        // protocol
        if ($this->carDamage->attachments->protocol) {
          $attachment = DamagesAttachmentsQuery::create()->findOneById($this->carDamage->attachments->protocol->id);
          if ($attachment instanceof DamagesAttachments && $attachment->getTemp() == 1) {
            $targetDir = Damages_Config::getInstance()->uploads->mainPath . $carData->getVin() . '/' . Damages_Config::getInstance()->uploads->subdirs->protocol;
            $targetFileName = sprintf(Damages_Config::getInstance()->uploads->patterns->protocol, $key);
            $attachment = $this->processAttachment($attachment, $targetDir, $targetFileName);
            $attachment->setCarDamageId($this->carDamage->id);
            $attachment->save();
          }
        }

        // waybill
        if ($this->carDamage->attachments->waybill) {
          $attachment = DamagesAttachmentsQuery::create()->findOneById($this->carDamage->attachments->waybill->id);
          if ($attachment instanceof DamagesAttachments && $attachment->getTemp() == 1) {
            $targetDir = Damages_Config::getInstance()->uploads->mainPath . $carData->getVin() . '/' . Damages_Config::getInstance()->uploads->subdirs->waybill;
            $targetFileName = sprintf(Damages_Config::getInstance()->uploads->patterns->waybill, $key);
            $attachment = $this->processAttachment($attachment, $targetDir, $targetFileName);
            $attachment->setCarDamageId($this->carDamage->id);
            $attachment->save();
          }
        }
      }
      foreach ($this->carDamage->invoices as $invoice) {
        $dbInvoice = null;
        if ($invoice->id) {
          $dbInvoice = DamagesInvoicesQuery::create()->findOneById($invoice->id);
        }
        if (!$dbInvoice) {
          $dbInvoice = new DamagesInvoices();
          $carDamage->addInvoices($dbInvoice);
        }
        $dbInvoice->setValue($invoice->value);
        $dbInvoice->setNumber($invoice->number);
        $dbInvoice->save();
      }
      foreach ($this->carDamage->notes as $note) {
        $dbNote = null;
        if ($note->id) {
          $dbNote = DamagesNotesQuery::create()->findOneById($note->id);
        }
        if (!$dbNote) {
          $dbNote = new DamagesNotes();
          $carDamage->addNotes($dbNote);
        }
        $dbNote->setValue($note->value);
        $dbNote->setNumber($note->number);
        $dbNote->setDictNoteTypeDefinitionId($note->noteTypeId);
        $dbNote->save();
      }
      $carDamage->save();
      $con->commit();
    } catch (Exception $exc) {
      $con->rollBack();
      throw $exc;
    }

    return new Damages_Methods_Response(true);
  }

  private function processAttachment(DamagesAttachments $attachment, $targetDir, $targetFileName) {
    if (!is_dir(APPLICATION_PATH . '/../public' . $targetDir))
      mkdir(APPLICATION_PATH . '/../public' . $targetDir, 0777, true);
    $sourcePath = APPLICATION_PATH . '/../public' . $attachment->getFilePath();
    if (!is_file($sourcePath))
      throw new Damages_Exception_App(Damages_Codes::NO_ATTACHMENT_FOUND);
    $sourceFname = $attachment->getName();
    $newFname = $targetFileName . Core_Tools::getFileExtension($sourceFname);
    $newPath = $targetDir . $newFname;
    $fullPath = APPLICATION_PATH . '/../public' . $newPath;
    if (rename($sourcePath, $fullPath)) {
      $attachment->setTemp(0);
      $attachment->setName($newFname);
      $attachment->setFilePath($newPath);
    }

    return $attachment;
  }

}